package com.soos.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.soos.dto.Result;
import com.soos.dto.UserDTO;
import com.soos.entity.Blog;
import com.soos.entity.Follow;
import com.soos.entity.User;
import com.soos.mapper.BlogMapper;
import com.soos.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.soos.service.IFollowService;
import com.soos.service.IUserService;
import com.soos.utils.ScrollResult;
import com.soos.utils.SystemConstants;
import com.soos.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.soos.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.soos.utils.RedisConstants.FEED_KEY;
import static com.soos.utils.SystemConstants.SCROLL_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryBlogById(int id) {
        Blog blog = getById(id);
        if(blog == null) {
            return Result.fail("笔记不存在");
        }
        queryBlogUser(blog);
        queryBlogLiked(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            queryBlogUser(blog);
            queryBlogLiked(blog);
        });
        return Result.ok(records);
    }
    //查询设置用户信息
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());
    }

    //查询用户是否点赞过
    private void queryBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            return ;
        }
        //1.得到用户登陆信息
        Long userId = user.getId();
        //2.判断该用户是否在redis的set集合存在,不存在,代表没有点赞过
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score != null);
    }

    /**
     * 1.实现点赞功能
     * 使用redis的set集合判断用户是否点赞过
     * 保证一个用户只能点赞一次,再点一次就取消点赞
     * 2.实现点赞排行榜的功能
     * redis的数据结构使用sortedSet,可以进行排序,按照访问时间进行排序,时间早的排在前面
     * 使用zrange进行排名
     * 使用zscore来判断用户是否点赞过
     * @param id 返回blog_id
     * @return 返回点赞是否成功
     */
    @Override
    public Result likeBlog(Long id) {
        //1.得到用户登陆信息
        UserDTO user = UserHolder.getUser();
        if(user == null) {
            return Result.fail("用户未登陆");
        }
        Long userId = user.getId();
        //2.判断该用户是否在redis的set集合存在,不存在,代表没有点赞过
        String key = BLOG_LIKED_KEY + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if(score == null) {//没有点赞过
            //2.1点赞数 += 1
            boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
            if(isSuccess) {
                //2.2把当前用户加入到set集合中
                stringRedisTemplate.opsForZSet().add(key,userId.toString(), System.currentTimeMillis());
            }
        }else {//3.点赞过
            //3.1点赞数-=1
            boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
            if(isSuccess) {
                //3.2从redis的set集合中移除
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }
        }
        return Result.ok();
    }

    /**
     * 查询id这个笔记的点赞排行榜
     */
    @Override
    public Result queryBlogLikes(int id) {
        //1.使用zSet的zRange查询在(0,4)的用户
        String key = BLOG_LIKED_KEY + id;
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        //2.解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        //3.根据id查询用户信息
        String strJoin = StrUtil.join(",", ids);
        List<User> users = userService.query().in("id", ids).
                last("ORDER BY field(id," + strJoin + ")").list();
        List<UserDTO> userDTOs = users.stream().
                map(user -> BeanUtil.toBean(user, UserDTO.class)).collect(Collectors.toList());
        //4.返回脱敏后的信息UserDTO
        return Result.ok(userDTOs);
    }

    /**
     * 1.实现将笔记推送到粉丝的收件箱
     * 2.使用滚动分页查询收件箱
     * @param blog 博文笔记
     * @return 返回博客id
     */
    @Override
    public Result saveBlog(Blog blog) {
        //因为之前已经上传图片了,信息都知道了,只有用户信息不知道
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        blog.setUserId(userId);
        // 2.保存探店博文
        boolean isSuccess = blogService.save(blog);
        if(!isSuccess) {
            return Result.fail("保存笔记失败");
        }
        // 3.查询所有的粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", userId).list();
        // 4.将笔记保存到粉丝的收件箱中
        for (Follow follow : follows) {
            //获取粉丝的id
            String key = FEED_KEY + follow.getUserId();
            //保存到粉丝的收件箱中
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    /**
     * 实现滚动分页查询
     * @param max 上一次查询的最小时间戳
     * @param offset 本次查询的最大时间戳
     * @return 返回 ScrollResult
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.得到当前用户的id
        Long userId = UserHolder.getUser().getId();
        //2.根据用户id查询自己的收件箱
        String key = FEED_KEY + userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset, SCROLL_PAGE_SIZE);
        if(typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        //3.解析出 blogId; 计算出offSet,LastId;
        Long minTime = 0L;//最小时间戳
        Integer os = 1;//偏移量大小->与最小时间戳相同的个数
        List<Long> blogs = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            String blogId = typedTuple.getValue();//blogId
            long score = typedTuple.getScore().longValue();//时间戳
            blogs.add(Long.valueOf(blogId));
            if(minTime == score) {
                os ++;
            }else{
                minTime = score;
                os = 1;
            }
        }
        //4.根据blogId得到blog信息
        String strJoin = StrUtil.join(",", blogs);
        List<Blog> blogList = blogService.query().in("id", blogs).last("ORDER BY field(id," + strJoin + ")").list();
        for (Blog blog : blogList) {
            queryBlogUser(blog);
            queryBlogLiked(blog);
        }
        //5.封装结果并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogList);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }
}